package com.xdhl.fu.common.core.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 高德地图工具类
 *
 * @author 朱力维
 * @time 2022/6/11 16:30
 */
public class GaodMapUtils {

    public static final String MAP_KEY = "c05dcd2d3be3082633bc1ae938ff0878";

    public static void main(String[] args) throws Exception {
        float distance = getDistance("九江", "庐山机场", "武汉", "天河机场");
        System.out.println("api调用距离结果:" + distance);
    }

    /**
     * 根据城市名和地址获取经纬度
     *
     * @param city    城市名
     * @param address 地址
     * @return 经纬度
     */
    public static String getLocation(String city, String address) {
        String url = String.format("https://restapi.amap.com/v3/geocode/geo?key=%s&address=%s&city=%s", MAP_KEY, address, city);
        String queryResult = HttpUtil.get(url);
        JSONObject result = JSONObject.parseObject(queryResult);
        if (null != result && "OK".equals(result.getString("info")) && "1".equals(result.getString("count"))) {
            return JSONObject.parseObject(result.getJSONArray("geocodes").get(0).toString()).getString("location");
        } else {
            return null;
        }
    }

    /**
     * 经纬度算出两点间距离（通过api调用计算）
     */
    public static float getDistance(String cityA, String addressA, String cityB, String addressB) throws Exception {
        String queryUrl = "http://restapi.amap.com/v3/distance?key=" + MAP_KEY + "&origins=" + getLocation(cityA, addressA) + "&destination=" + getLocation(cityB, addressB) + "&type=0";
        String queryResult = HttpUtil.get(queryUrl);
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONArray ja = job.getJSONArray("results");
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        Float floatVal = Float.parseFloat(jobO.get("distance").toString());
        return Double.valueOf(MathUtils.priceDivide(floatVal, 1000D)).floatValue();
    }

}
